import android.app.Application
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import com.martin.lib_base.base.BaseApplication

lateinit var appContext: Application

fun setApplicationContext(context: Application) {
    appContext = context
}

/**
 * Fragment获取全局ViewModel
 */
inline fun <reified VM: ViewModel> Fragment.getAppViewModel() : VM {
    (requireActivity().application as? BaseApplication).let {
        if (it == null) {
            throw NullPointerException("Application does not inherit from BaseApplication")
        } else {
            return it.getAppViewModelProvider()[VM::class.java]
        }
    }
}

/**
 * Fragment获取全局ViewModel
 */
inline fun <reified VM: ViewModel> AppCompatActivity.getAppViewModel() : VM {
    (application as? BaseApplication).let {
        if (it == null) {
            throw NullPointerException("Application does not inherit from BaseApplication")
        } else {
            return it.getAppViewModelProvider()[VM::class.java]
        }
    }
}